package org.odk.clinic.android.activities;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.odk.clinic.adroid.service.Concept;
import org.odk.clinic.android.R;
import org.odk.clinic.android.adapters.PatientAdapter1;

import org.odk.clinic.android.database.ClinicAdapter;
import org.odk.clinic.android.database.SQLiteAdapter;
import org.odk.clinic.android.openmrs1.concept_name;
import org.odk.clinic.android.openmrs1.person_name;

import custom_View.aperson;



import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;


public class ListPatientActivity2 extends ListActivity {
	private SQLiteAdapter mDB;
	private Cursor mCursor;
	static int mid;
	int progress = 0 ;
	private TextWatcher mfilterwatcher;
	
	private ListView ls;
	private concept_name cna;
	
	public static final int BARCODE_CAPTURE = 2;
	private ArrayAdapter<aperson> mpersonAdapter;
	private ArrayList<aperson> maperson = new ArrayList<aperson>();
	private ProgressDialog mprogress = null;
	private Runnable viewpatients;
	//
	private static final String KEY_SEARCH = "search";
	
	private EditText msearch;
	private Button btnfind;
	private InputMethodManager mInputMethodManager;
	
	
	//////
	protected void onCreate(Bundle ici){
		super.onCreate(ici);

		
		setContentView(R.layout.list_patient);

		if (!ClinicAdapter.storageReady()) {
			showCustomToast(getString(R.string.error, R.string.storage_error));
			finish();
		}
		
		 
		/////////////
		//mDB = new SQLiteAdapter(this);
		//mDB.open();
		
		//Concept cs = new Concept();
		//ArrayList<String> lt  = cs.GetConcept();
		//cna = new concept_name();
		//for(int i=1 ;i<=lt.size();i++){
			
			//cna.setConceptName(lt.get(i).toString());
			//mDB.createConcept(cna);
		//}
		
		//setListAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, lt));
		//getData();
		
		
		/*viewpatients = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				getPatients();
			}
		};
		Thread thread = new Thread(null, viewpatients,"ViewPatients");
		thread.start();
		mprogress = ProgressDialog.show(ListPatientActivity2.this, "Please wait...", "Retrieving data...",true);*/
		
		//
		// used to hide keyboard after search
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		msearch = (EditText)this.findViewById(R.id.search);
		msearch.addTextChangedListener(new TextWatcher(){
		
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if(mpersonAdapter != null){
				mpersonAdapter.getFilter().filter(s);
				
				}
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		
		btnfind = (Button)this.findViewById(R.id.btnsearch);
		btnfind.setOnClickListener(new View.OnClickListener() {
		@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			 String searchStr = msearch.getText().toString();
             if (searchStr.length() > 0) {
                     mInputMethodManager.hideSoftInputFromWindow(
                    		 msearch.getWindowToken(), 0);
                     getPatients(searchStr);
             } else  {
            	 	getPatients();	
             }
            
			/*Intent i = new Intent("com.google.zxing.client.android.SCAN");
			try {
				startActivityForResult(i, BARCODE_CAPTURE);
			} catch (ActivityNotFoundException e) {
				Toast t = Toast.makeText(getApplicationContext(),
						getString(R.string.error, R.string.barcode_error),
						Toast.LENGTH_LONG);
				t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				t.show();
			}*/
     }
});
				
				
	}
		
		
		
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent){
		if (requestCode == BARCODE_CAPTURE && intent != null) {
			String sb = intent.getStringExtra("SCAN_RESULT");
			if (sb != null && sb.length() > 0) {
				msearch.setText(sb);
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);

	}
	
	private Runnable returnRes = new Runnable(){
		@Override
		public void run(){
			if(maperson != null && maperson.size()>0){
				mpersonAdapter.notifyDataSetChanged();
				for(int  i = 0;i < maperson.size();i++)
					mpersonAdapter.add(maperson.get(i));
				
			}
			mprogress.dismiss();
			mpersonAdapter.notifyDataSetChanged();
		}
	};
	private void getPatients(){
		getPatients(null);
	}
	private void getPatients(String stringSearch) {
		
		aperson a;
		SQLiteAdapter ca = new SQLiteAdapter(this);
		DateFormat mdf = new SimpleDateFormat("dd-mm-yyyy");
		ca.open();
		Cursor c = null;
		if(stringSearch != null){
			c = ca.find_patients(stringSearch);
		}
		else{
		c = ca.getAllPerson();
		}
		if (c != null && c.getCount() >= 0) {
			maperson.clear();
			int personid = c
				.getColumnIndex(SQLiteAdapter.KEY_PATIENT_ID);
			int givenName = c
				.getColumnIndex(SQLiteAdapter.KEY_GIVENNAME);
			int midlename = c
				.getColumnIndex(SQLiteAdapter.KEY_MIDLENAME);
			int familyname = c
				.getColumnIndex(SQLiteAdapter.KEY_FAMILYNAME);
			int birth = c
				.getColumnIndex(SQLiteAdapter.KEY_BIRTH);
			int gender = c
				.getColumnIndex(SQLiteAdapter.KEY_GENDER);
			if (c.getCount() > 0) {
				do {
					a = new aperson();
					a.setPatientId(c.getInt(personid));
					a.setGivenName(c.getString(givenName));
					a.setMiddleName(c.getString(midlename));
					a.setFamily_Name(c.getString(familyname));
					try{
						a.setBirth(mdf.parse(c.getString(birth)));
					}
					catch(ParseException e){
						e.printStackTrace();
					}
					a.setGender(c.getString(gender));
					maperson.add(a);
				} while (c.moveToNext());
			}
		}
		refreshView();

		if (c != null) {
			c.close();
		}
		ca.close();
		
	}

	private void refreshView() {
		
		mpersonAdapter = new PatientAdapter1(this, R.layout.patient_list_item1, maperson);
		setListAdapter(mpersonAdapter);
	}
	
	//get data
	/*private void getData(){
		mCursor = mDB.getAllPerson();
		startManagingCursor(mCursor);
		String[] from = new String[]{SQLiteAdapter.KEY_GIVENNAME};
		int[] to = new int[]{R.id.text1};
		SimpleCursorAdapter per = new SimpleCursorAdapter(this,R.layout.patient_list_item1,mCursor,from,to);
		setListAdapter(per);
		
	}*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_patient, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.addpatient :
			Intent i  = new Intent(this,NewPatientActivity1.class);
			startActivity(i); break;
		}
		return true;
	}
	
	@Override
	protected void onListItemClick(ListView l, View v,int position, long id){
		super.onListItemClick(l, v, position, id);
		
		aperson ap = (aperson)getListAdapter().getItem(position);
		mid = ap.getPatientId();
		Show_Alert_box(v.getContext(), "Please choose action", position);
		
}
	
	@Override
	protected void onStart(){
		super.onStart();
		
	}
	@Override
	protected void onPause() {
		super.onPause();

	}
	@Override
	protected void onResume() {
	    super.onResume();
	    String s = msearch.getText().toString();
	    if(s !=null && s.length()>0){
	    	getPatients(s);
	    }
	    else{
	    
	    getPatients();
	    }
	  
 	    super.onResume();
	   
	}
	@Override
	protected void onDestroy(){
		super.onDestroy();
		msearch.removeTextChangedListener(mfilterwatcher);
	}
	@Override
    protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putString(KEY_SEARCH, msearch.getText().toString());
    }
	private void showCustomToast(String message) {
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.toast_view, null);

		// set the text in the view
		TextView tv = (TextView) view.findViewById(R.id.message);
		tv.setText(message);

		Toast t = new Toast(this);
		t.setView(view);
		t.setDuration(Toast.LENGTH_LONG);
		t.setGravity(Gravity.CENTER, 0, 0);
		t.show();
	}
	public void Show_Alert_box(Context context, String message, int position){
		final int pos = position;
		final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
				alertDialog.setTitle("Choose options belows");
				alertDialog.setButton("Delete >>", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
					final AlertDialog delDialog = new AlertDialog.Builder(ListPatientActivity2.this).create();
						delDialog.setTitle("Are you sure to delete ?");
						TextView tv1 = new TextView(ListPatientActivity2.this);
						LayoutParams tv1Layout = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
						tv1.setLayoutParams(tv1Layout);
						tv1.setText("ID :" + String .valueOf(mid));
						LinearLayout layout = new LinearLayout(ListPatientActivity2.this);
						layout.setOrientation(LinearLayout.VERTICAL);
						layout.addView(tv1);
						
						delDialog.setButton("OK", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								mDB = new SQLiteAdapter(ListPatientActivity2.this);
								mDB.open();
								mDB.deletePerson(mid);
								getPatients();
								
							}
						});
						delDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								delDialog.dismiss();
							}
						});
						delDialog.setMessage("Pass");
						delDialog.show();
					}
				});
				alertDialog.setButton2("Cancel >>", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});
				alertDialog.setButton3("Details >>", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						Intent j = new Intent(ListPatientActivity2.this,DetailPatientActivity.class );
						startActivity(j);
					}
				});
				alertDialog.setMessage(message);
				alertDialog.show();
				
	}
	
}

